<template>
  <div style="padding: 10px 15px" class="all">
    <!-- 查询条件-->
    <div class="filter-container">
      <el-select
        v-if="this.logincpnid == 'system'"
        v-model="selectparms.cpnID"
        filterable
        clearable
        class="filter-item"
        placeholder="请选择企业"
        @change="CpnselectFn($event)"
        :filter-method="cpnmatch"
         @clear="cpnmatch"
      >
        <el-option
          v-for="item in cpnoptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span v-html="item.label" />
        </el-option>
      </el-select>
      <el-col :span="3" style="margin-right: 10px">
        <el-date-picker
          type="date"
          placeholder="请选择账单日期"
          v-model="selectparms.date"
          style="width: 100%; margin-right: 10px"
          format="yyyy-MM-dd"
        ></el-date-picker>
      </el-col>
      <el-col :span="3" style="margin-right: 10px">
        <el-date-picker
          type="date"
          placeholder="请选择账单日期"
          v-model="selectparms.edate"
          style="width: 100%; margin-right: 10px"
          format="yyyy-MM-dd"
        ></el-date-picker>
      </el-col>
      <el-button
        class="filter-item seachbttn"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >查询</el-button
      >
    </div>
    <div
      class="filter_fenge"
      style="border: none; border-top: 1px solid #d1ddeb"
    ></div>
    <div class="filter-container">
      <el-button
        :loading="downloadLoading"
        class="filter-item bttnleft"
        type="primary"
        icon="el-icon-download"
        @click="downloadRcBatch(1)"
        >批量下载ERP平台对账单</el-button
      >
    </div>
    <!--查询条件 end-->
    <!--弹出层 end-->

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="HeartbeatData"
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
      stripe
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column type="index" width="50" label="序号"> </el-table-column>
      <el-table-column label="企业名称" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.cpnid }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="账单日期"
        align="left"
        width="160"
        min-width="180px"
      >
        <template slot-scope="{ row }">
          <span>{{ row.dtStr }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="130">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="downloadRcERP(scope.row)"
            >下载当日账单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="listQuery.total > 0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData(this)"
    />
  </div>
</template>
<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { AjaxToken, TipConfirm } from "@/api/common";
import { SelectAjax } from "@/api/common";
import { Jurisdiction } from "@/api/common";
import sessionStorage from "@/api/Storage";
import "url-search-params-polyfill"; //兼容IE，否则无法识别URLSearchParams
import commconfig from "@/comm.json";
import { date } from "jszip/lib/defaults";
import PinYinMatch from "pinyin-match";

export default {
  name: "ReconciliationToExcelERP",
  components: { Pagination },
  data() {
    return {
      HeartbeatData: [],
      cpnoptions: [],
      cpnactlstoptions: [],
      logincpnid: "",
      multipleSelection: [],
      formLabelWidth: "120px",
      RcncbtchData: null,
      downloadLoading: false,
      downloadRcERPLoading: false,
      downloadRcBatchLoading: false,
      downloadRcBatchERPLoading: false,
      listQuery: {
        title: "",
        total: 0,
        page: 1,
        limit: 10,
      },
      selectparms: {
        cpnID: "",
        act: "ERP",
        date: "",
        edate: "",
      },
      listLoading: false,
      dialogFormVisible: false,
      dialogdetailsVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加",
      },
    };
  },
  methods: {
    cpnmatch(val) {
      if (val) {
        let result = [];
        this.cpnoptions.forEach((item) => {
          let matchRes = PinYinMatch.match(item.label, val);
          if (matchRes) {
            result.push(item);
          }
        });
        this.cpnoptions = result;
      } else {
        this.cpnid = "";
        this.cpnoptions = backstage.GeCpntListItems(this);
      }
    },

    CpnselectFn(e) {
      this.cpnactlstoptions = [];
      this.selectparms.cpnID = e;
      this.selectparms.act = "";
      backstage.GetCpnActList(this);
    },
    //弹层关闭
    handleClose() {},
    //权限
    Jurisdiction(moduleActionName) {
      return Jurisdiction(moduleActionName, this);
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //多选赋值
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //搜索
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchData();
    },
    // 查询
    fetchData() {
      var params = new URLSearchParams();
      params.append(
        "Parms",
        '{"page":' +
          this.listQuery.page +
          ',"rows":' +
          this.listQuery.limit +
          "}"
      );
      if (this.selectparms.date == "") {
        this.$message({
          showClose: true,
          message: "请选择日期",
          type: "error",
        });
        return;
      }
      if (this.selectparms.edate == "") {
        this.$message({
          showClose: true,
          message: "请选择结束日期",
          type: "error",
        });
        return;
      }


      var ed = new Date(new Date(this.selectparms.date).toLocaleDateString());
      var nd = new Date(new Date(this.selectparms.edate).toLocaleDateString());
      var now = new Date(new Date().toLocaleDateString());
      if(ed>nd){
        this.$message({
          showClose: true,
          message: "开始日期不能大于结束日期",
          type: "error",
        });
        return;
      }
     
      if (this.selectparms.cpnID == "") {
        this.$message({
          showClose: true,
          message: "请选择企业",
          type: "error",
        });
        return;
      }
      params.append("account", this.selectparms.act);
      params.append("cpnid", this.selectparms.cpnID);
      params.append("type", "0");
      params.append(
        "date",
        this.selectparms.date == ""
          ? ""
          : new Date(this.selectparms.date).toLocaleDateString()
      );

      params.append(
        "edate",
        this.selectparms.edate == ""
          ? ""
          : new Date(this.selectparms.edate).toLocaleDateString()
      );
      this.selectparms.date =
        this.selectparms.date == ""
          ? ""
          : new Date(this.selectparms.date).toLocaleDateString();
      this.selectparms.edate =
        this.selectparms.edate == ""
          ? ""
          : new Date(this.selectparms.edate).toLocaleDateString();
      this.listLoading = true;
      backstage.GetRcdateLst(this, params);
    },
    //批量下载
    downloadRcBatch(type) {
      var arr = this.multipleSelection;
      var dates = [];
      if (arr == undefined || arr.length <= 0) {
        this.$message({
          showClose: true,
          message: "请至少选中一行",
          type: "error",
        });
        return;
      } else {
        for (var i = 0; i < arr.length; i++) {
          dates.push(arr[i].dtStr);
        }
      }
      var params = new URLSearchParams();
      params.append("account", this.selectparms.act);
      params.append("cpnid", this.selectparms.cpnID);
      params.append("type", type);
      params.append(
        "date",
        this.selectparms.date == ""
          ? ""
          : new Date(this.selectparms.date).toLocaleDateString()
      );
      params.append(
        "date",
        this.selectparms.edate == ""
          ? ""
          : new Date(this.selectparms.edate).toLocaleDateString()
      );
      this.selectparms.date =
        this.selectparms.date == ""
          ? ""
          : new Date(this.selectparms.date).toLocaleDateString();
      this.selectparms.edate =
        this.selectparms.edate == ""
          ? ""
          : new Date(this.selectparms.edate).toLocaleDateString();
      if (type == 0) {
        this.downloadRcBatchLoading = true;
      } else {
        this.downloadRcBatchERPLoading = true;
      }
      const loading = this.$loading({
        lock: true,
        text: "后台账单下载中,请勿关闭页面",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      backstage.downloadRcBatch(this, params, dates, type, loading);
    },
    //单个下载ERP
    downloadRcERP(row) {
      if (this.selectparms.date == "") {
        this.$message({
          showClose: true,
          message: "请选择日期",
          type: "error",
        });
        return;
      }
      if (this.selectparms.cpnID == "") {
        this.$message({
          showClose: true,
          message: "请选择企业",
          type: "error",
        });
        return;
      }
      this.downloadRcBatchLoading = true;
      const loading = this.$loading({
        lock: true,
        text: "后台账单下载中,请勿关闭页面",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var year = new Date(row.dtStr).getFullYear();
      var month = (new Date(row.dtStr).getMonth() + 1).toString();
      var day = new Date(row.dtStr).getDate().toString();
      var sec = new Date(new Date(row.dtStr).toLocaleDateString());
      var now = new Date(new Date().toLocaleDateString());
      
      var day2 = "";
      if (day.length <= 1) {
        day2 = "0" + day;
      } else {
        day2 = day;
      }
      var month2 = "";
      if (month.length <= 1) {
        month2 = "0" + month;
      } else {
        month2 = month;
      }
      var lastmouthtime = new Date(row.dtStr);
      lastmouthtime = lastmouthtime.setDate(lastmouthtime.getDate() + 0);
      lastmouthtime = new Date(lastmouthtime);
      var lastday = lastmouthtime.getDate().toString();
      var lastmouth = (lastmouthtime.getMonth() + 1).toString();
      var lastyear = lastmouthtime.getFullYear();
      var day3 = "";
      if (lastday.length <= 1) {
        day3 = "0" + lastday;
      } else {
        day3 = lastday;
      }
      var month3 = "";
      if (lastmouth.length <= 1) {
        month3 = "0" + lastmouth;
      } else {
        month3 = lastmouth;
      }
      var name = year + month2 + day2 + "_" + lastyear + month3 + day3;
      this.downloadRcERPLoading = true;
      window.open(
        "https://wpaydp.s3.cn-northwest-1.amazonaws.com.cn/Alipay/cpn%3D" +
          this.selectparms.cpnID +
          "/year%3D" +
          year +
          "/month%3D" +
          month +
          "/day%3D" +
          day +
          "/" +
          name +
          ".csv",
        "_blank"
      );
      this.downloadRcERPLoading = false;
      loading.close();
    },
  },

  //初始化
  created() {
    var userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    this.logincpnid = userinfo.cpnId;
    backstage.GeCpntListItems(this);
    if (this.logincpnid != "system") {
      this.cpnactlstoptions = [];
      this.selectparms.cpnID = this.logincpnid;
      this.selectparms.act = "";
      //backstage.GetCpnActList(this);
    }
  },
};
//后台事件
var backstage = {
  //获取MngrLog集合
  GetRcdateLst: function (thisobj, params) {
    AjaxToken(
      thisobj,
      "GetRcdateLst",
      params,
      "post",
      function (res) {
        thisobj.listLoading = false;
        var body = res.data.data;
        thisobj.HeartbeatData = [];
        thisobj.HeartbeatData = body.rows;
        thisobj.listQuery.page = body.page;
        thisobj.listQuery.total = body.records;
      },
      function (err) {
        thisobj.listLoading = false;
      }
    );
  },
  GeCpntListItems: function (thisobj) {
    SelectAjax(
      "GeCpntListItems",
      function (response) {
        var body = response.data;
        thisobj.cpnoptions = [];
        body.data.forEach((element) => {
          thisobj.cpnoptions.push({
            value: element.value,
            label: element.text,
          });
        });
      },
      function (error) {}
    );
  },
  GetCpnActList: function (thisobj) {
    SelectAjax(
      "GetCpnActList?val=&cpnid=" + thisobj.selectparms.cpnID + "",
      function (response) {
        var body = response.data;
        thisobj.cpnactlstoptions = [];
        if (body.data.length > 0) {
          thisobj.selectparms.act = body.data[0].value;
        }
        body.data.forEach((element) => {
          thisobj.cpnactlstoptions.push({
            value: element.value,
            label: element.text,
          });
        });
      },
      function (error) {}
    );
  },
  downloadRcBatch: function (thisobj, params, datejson, type, loading) {
    AjaxToken(
      thisobj,
      "DownloadRcBatch?date=" +
        thisobj.selectparms.date +
        "&edate=" +
        thisobj.selectparms.edate +
        "&account=" +
        thisobj.selectparms.act +
        "&dates=" +
        JSON.stringify(datejson) +
        "&type=" +
        type +
        "&cpnid=" +
        thisobj.selectparms.cpnID +
        "",
      params,
      "get",
      function (res) {
        thisobj.downloadRcBatchLoading = false;
        thisobj.downloadRcBatchERPLoading = false;
        thisobj.downloadLoading = false;
        loading.close();
        var body = res.data;
        if (body.success) {
          if (body.data != "") {
            window.location.href = body.data;
          } else {
            thisobj.$message({
              showClose: true,
              message: body.message,
              type: "error",
            });
          }
        } else {
          thisobj.$message({
            showClose: true,
            message: body.message,
            type: "error",
          });
        }
      },
      function (err) {
        loading.close();
        thisobj.downloadLoading = false;
      }
    );
  },
};
</script>
<style scoped>
.filter-container {
  height: 46px;
}
</style>